# dist.auk
# Tim Menzies
# Sept 12, 2012

function kth(k,row1,from,_Rows,normp,out,	\
             row2,n,sort,i,diff) {
  for(i in from) {
    row2=from[i]
    if (row2==row1) continue
    diff[i]["="]= row2
    diff[i]["x"]= dist(row1,row2,_Rows,normp)}
  n=asort(diff,sort,"xsort")
  k =  n <  k ? n : k
  for(i=1;i<=k;i++) 
    out[i]= sort[i]["="]
  return k
}
function dist(row1,row2,_Rows,normp,   col,sum,ws,w1,x,y){
  if (row1==row2)  return 0
  for(col in np) {
    if (gp[col]) continue
    w1 = w[col]; 
    if (w1==0) continue
    x  = d[row1][col]
    y  = d[row2][col]
    if (x=="?" && y=="?") continue 
    sum += w1 * dist1(x,y,col,_Rows,normp)
    ws  += w1 }
  return sqrt(sum)/sqrt(ws + 0.000001)
}
function dist1(x,y,col,_Rows,normp) {
  if (x == y)   return 0
  if (!np[col]) return value(x) != value(y)
  if (y == "?") {
    x  = norm(x,col,hi,lo,normp)
    y  = x > 0.5 ? 0 : 1
  } else if (x == "?") {
    y = norm(y,col,hi,lo,normp)
    x = y > 0.5 ? 0 : 1
  } else {
    x = norm(x,col,hi,lo,normp)
    y = norm(y,col,hi,lo,normp) } 
  return (x - y)^2 
}
function norm(x,col,hi,lo,  normp) {
  if (normp)
    return (x - lo[col])/(hi[col] - lo[col]+0.00001)
  else return x
}
function value(x) { return x=="?" ? "WiErDLie" : x }
